import uuid

from kivy.properties import ListProperty, StringProperty, OptionProperty
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.tabbedpanel import TabbedPanelItem

from common import KvLoad, get_conf, write_conf_by_option

default_grid_dict = {'file_path': '', 'group': 'grid'}


class InteractPanel(BoxLayout):
    panel_text_list = ListProperty()
    toggle_column_list_data = ListProperty()
    # 互动音轨播放状态
    interact_panel_pay_state = OptionProperty('stop', options=["stop", "play", "pause"])

    def __init__(self, **kwargs):
        KvLoad.load(__file__)
        super().__init__(**kwargs)
        self.last_panel_item_index = 0  # 当前的panel_item的index  默认为0
        self.init_data()

    def init_data(self):
        conf = get_conf()
        self.panel_text_list = conf.get_list('interact_track', 'panel_text_list')
        self.init_toggle_column()

    def init_toggle_column(self):
        self.toggle_column_list_data.clear()
        for title in self.panel_text_list:
            self.add_toggle_column(title)

    def add_toggle_column(self, title: str):
        if title not in self.panel_text_list:
            self.panel_text_list.append(title)
        write_conf_by_option('interact_track', 'panel_text_list', self.panel_text_list)
        new_uuid = str(uuid.uuid4())
        self.toggle_column_list_data.append({'text': title, 'group': 'mc', 'uuid': new_uuid})
        self.ids.id_tabbed_panel.add_widget(PanelBoxLayout(text=title, uuid=new_uuid))

    def add_toggle_button(self):
        """添加栏"""
        conf = get_conf()
        default_new_title = conf.get('interact_track', 'default_new_title')
        new_number = self.get_title_new_number(default_new_title)
        self.add_toggle_column(f'{default_new_title}{new_number}')

    def get_title_new_number(self, new_name):
        last_item = self.panel_text_list[-1]
        if new_name in last_item:
            last_number = int(last_item.split(new_name)[1])
        else:
            last_number = 0
        new_number = last_number + 1
        return new_number

    def on_switch_panel_by_toggle_column(self, column_uuid):
        goto_index = 0
        for index, grid_data in enumerate(self.toggle_column_list_data):
            if grid_data.get('uuid') == column_uuid:
                goto_index = index
                break

        if self.last_panel_item_index == goto_index:
            return

    def add_play_grid_button(self):
        grid_data = default_grid_dict.copy()
        grid_data.update(uuid=str(uuid.uuid4()))
        self.ids.id_tabbed_panel.current_tab.music_list_data.append(grid_data)


class MyToggleButton(ToggleButtonBehavior, Button):
    uuid = StringProperty()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.bind(on_touch_down=self.on_touch_down_double_tap_listen)

    def on_release(self):
        self.parent.parent.parent.parent.on_switch_panel_by_toggle_column(self.uuid)

    def on_touch_down_double_tap_listen(self, widget, touch):
        _ = widget
        if self.disabled:
            return

        touch_pos = touch.pos
        if not self.collide_point(*touch_pos):
            return False

        if touch.is_double_tap:
            pass  # 双击


class PanelBoxLayout(TabbedPanelItem):
    uuid = StringProperty()
    music_list_data = ListProperty()
    # 互动音轨播放状态
    panel_pay_state = OptionProperty('stop', options=["stop", "play", "pause"])

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.ids.id_grid.bind(width=self.update_cols)
        self.init_data()

    def init_data(self):
        conf = get_conf()
        panel_text_list = conf.get_list('interact_track', 'panel_text_list')
        option_index = f'panel_music_list_index{panel_text_list.index(self.text)}'
        music_list = conf.get_list('interact_track', option_index)
        if music_list:
            music_list_data = list()
            for file_path in music_list:
                grid_data = default_grid_dict.copy()
                grid_data.update(file_path=file_path, uuid=str(uuid.uuid4()))
                music_list_data.append(grid_data)
            self.music_list_data = music_list_data
        else:
            grid_data = default_grid_dict.copy()
            grid_data.update(uuid=str(uuid.uuid4()))
            self.music_list_data = [grid_data]

    def update_cols(self, widget, width):
        _ = widget
        self.ids.id_grid.cols = int(width / 360)

    def on_music_list_data(self, widget, data):
        _ = widget
        store_data = [grid.get('file_path') for grid in data if grid.get('file_path')]
        if store_data:
            conf = get_conf()
            panel_text_list = conf.get_list('interact_track', 'panel_text_list')
            option_index = f'panel_music_list_index{panel_text_list.index(self.text)}'
            origin_store_data = conf.get_list('interact_track', option_index)
            if store_data != origin_store_data:
                write_conf_by_option('interact_track', option_index, store_data)

    def grid_on_dismiss_by_uuid(self, uuid_):
        pop_index = None

        for index, grid in enumerate(self.music_list_data):
            if grid.get('uuid') == uuid_:
                pop_index = index
                break
        if pop_index:
            self.music_list_data.pop(pop_index)

    def grid_on_file_path(self, uuid_, file_path):
        update_index = None
        for index, grid in enumerate(self.music_list_data):
            if grid.get('uuid') == uuid_:
                update_index = index
                break
        if update_index:
            self.music_list_data[update_index]['file_path'] = file_path
            self.on_music_list_data(None, self.music_list_data)
